package csc411;

import java.util.ArrayList;
import java.net.*;

// History Manager manages the list of server replies/responses
public class RequestsManager {

	private ArrayList requests;

	public RequestsManager() {
		requests = new ArrayList();
	}

	public Request storeNewRequest(InetAddress address, int port, int requestId) {

		// check if request already exists for address/port/requestId

		Request newRequest = new Request(address, port, requestId);

		this.requests.add(newRequest);

		return newRequest;

	}

	public Request storeNewRequest(InetAddress address, int port, int requestId, String response) {

		// check if request already exists for address/port/requestId

		Request newRequest = new Request(address, port, requestId, response);

		this.requests.add(newRequest);

		return newRequest;

	}

	public Request updateRequest(InetAddress address, int port, int requestId, String response) throws Exception {

		Request request = this.getRequest(address, port, requestId);

		request.setResponse(response);

		return request;

	}

	public Request getRequest(InetAddress address, int port, int requestId)
			throws Exception {

		Request newRequest = null;

		for (int i = 0; i < this.requests.size(); i++) {

			Request request = (Request) this.requests.get(i);

			if (request.equal(address, port, requestId)) {
				// we found a duplicate in the list
				// ie not a new request
				return request;
			}
		}

		if (newRequest == null) {
			throw new Exception("Reply does not exist");
		}


		return newRequest;
	}

	public boolean isNewRequest(InetAddress address, int port, int requestId) {

		boolean value = true;

		// find if request is new
		for (int i = 0; i < this.requests.size(); i++) {

			Request request = (Request) this.requests.get(i);

			if (request.equal(address, port, requestId)) {
				// we found a duplicate in the list
				// ie not a new request
				return false;
			}
		}

		return value;
	}

	public boolean isDuplicateRequest(InetAddress address, int port, int requestId) {
		boolean value = this.isNewRequest(address, port, requestId);

		return !value;
	}

	public void printRequestList() {
		System.out.println("Request History list");
		System.out.println("--------------------");
		if (this.requests.size() == 0) {

			System.out.println("  Empty");

		} else {

			for (int i = 0; i < this.requests.size(); i++) {

				Request request = (Request) this.requests.get(i);
				System.out.println(i + ":" + request.toString());

			}
		}

		System.out.println();

	}
}
